package com.meizhao.admin.interceptor;


import com.meizhao.admin.configuration.ConfigProperties;
import com.meizhao.admin.exception.CommonException;
import com.meizhao.admin.service.RedisService;
import com.meizhao.admin.utils.HttpUtils;
import com.meizhao.admin.utils.ResultCode;
import com.meizhao.admin.utils.constants.Keys;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class AllInterceptor extends HandlerInterceptorAdapter {

	private ConfigProperties configProperties;

	private RedisService<String, String> redisService;

	@Autowired
	public AllInterceptor(ConfigProperties configProperties, RedisService<String, String> redisService) {
		this.configProperties = configProperties;
		this.redisService = redisService;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		String currentUrl = HttpUtils.getURI(request);
		log.info("current url: "+currentUrl+", ip: "+HttpUtils.getIpAddress());
		if (HttpUtils.checkUrl(currentUrl,configProperties.getPassUrls())
			&& HttpUtils.checkUrl(currentUrl, configProperties.getResourceUrls())) {
			return checkAuth(request, response, currentUrl);
		}
        return true;
	}

	private boolean checkAuth(HttpServletRequest request, HttpServletResponse response, String currentUrl){

		String token = HttpUtils.getTokenByRequest();
		if(StringUtils.isBlank(token) || StringUtils.equals(token,"null")){
			log.info("没有获取到{}", Keys.TOKEN);
			noPassHandler(request, response, ResultCode.UNABLEUSER);
			return false;
		}
		String userId = "";
		String prefix = "";
		try {
			String[] decodes = HttpUtils.decodeToken(token);
			if(decodes != null) {
				prefix = decodes[0];
				userId = decodes[1];
			}
		}catch (Exception e){
			e.printStackTrace();
			noPassHandler(request, response, ResultCode.UNABLEUSER);
			return false;
		}

		if(Keys.REDISKEY_ADMIN_PREFIX.equals(prefix)){
			if(!HttpUtils.checkAuthUrl(currentUrl, configProperties.getAdminUrlPrefixs())){
				noPassHandler(request, response, ResultCode.NOPERMISSION);
				return false;
			}
		}
		if(Keys.REDISKEY_USER_PREFIX.equals(prefix)){
			if(!HttpUtils.checkAuthUrl(currentUrl, configProperties.getApiUrlPrefixs())){
				noPassHandler(request, response, ResultCode.NOPERMISSION);
				return false;
			}

		}
		String key = prefix+ Keys.REDIS_KEY_DELIMITER+userId;
		if(StringUtils.equals(redisService.getValue(key), token)){
				redisService.expire(key,
						configProperties.getSessionTimeoutMinus(),
						TimeUnit.MINUTES);
		}else{
			noPassHandler(request, response, ResultCode.UNABLEUSER);
			return false;
		}
		return true;
	}


	private void noPassHandler(HttpServletRequest request, HttpServletResponse response,
							   ResultCode errorCode){
		if(HttpUtils.isAjax(request)){
			throw new CommonException(errorCode);
		}else{
			try {
				response.sendRedirect(request.getContextPath() + configProperties.getAdminNoLoginUrl() );
			}catch (IOException e){
				e.printStackTrace();
			}
		}
	}


	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		super.postHandle(request, response, handler, modelAndView);
	}
}
